<template>
  <div>
    <div class="main-content">
      <div class="type-list">
        <span class="type-card" v-for="(item, key) in foodList" :key="key">{{ key }}</span>
      </div>
      <div class="item-list">
        <!-- 根据食物的type分出大盒子装同一种type的食物 -->
        <div class="food-type" v-for="type in foodList" :key="type[0].id">
          <div class="type-name">{{ type[0].foodType }}</div>
          <!-- 大盒子里装每种食物，每种食物就是一个food-card -->
          <div class="food-card" v-for="item in type" :key="item.id">
            <span class="img-box"><img :src="item.imgUrl" alt="" /></span>
            <span class="text-box">
              <span class="food-name">{{ item.foodName }}</span>
              <span class="food-intro">{{ item.intro }}</span>
              <span class="food-rate">月售9999+ 评分：{{ item.rate }}</span>
              <span class="food-buy">
                <span class="price">¥ {{ item.price }}</span>
                <span class="buy-btn">
                  <buy-btn :name="item.foodName" :id="item.id" :price="item.price" :imgUrl="item.imgUrl" @createFood="createFood" @addFood="addFood" @moveFood="moveFood" @reduceFood="reduceFood" @changeFood="changeFood"> </buy-btn>
                </span>
              </span>
            </span>
          </div>
        </div>
      </div>
      <div class="footer" @click="handlePay" v-text="totalPrice == 0 ? '待支付' : '去支付  ¥  ' + totalPrice"></div>
    </div>
  </div>
</template>

<script>
import { request } from '../utils/request'
import BuyBtn from '../components/BuyBtn.vue'
export default {
  components: {
    BuyBtn
  },
  data() {
    return {
      //
      foodList: {},
      order: [],
      totalPrice: 0,
      // hasAddFood:false
    }
  },
  computed: {
    // 可以用computed属性动态监测当前页面是否添加了食物，也可以直接监测totalprice是否为0，如果有0元商品，那么最好用hasAddFood
    //对于任何复杂逻辑，你都应当使用计算属性。计算属性可以随其依赖的变量更新而更新。而data中的属性则不可以，除了对象引用。
    // 也可以想象，computed属性和其依赖变量的动态绑定就等于模板{{}}与data中的数据的动态绑定，当然{{}}也可以动态绑定computed属性
    hasAddFood() {
      return this.order.length != 0
    }
  },
  methods: {
    handlePay() {
      console.log(this.order)
      this.$store.commit('setOrders',this.order)
      this.$router.push({ path: '/pay', query: { order: this.order, totalPrice: this.totalPrice } })
    },
    // 监听子组件,这里做的不好的一点是：在子组件就提前进行了判断，根据判断结果一共发出了4种事件
    // 实际上如果放到父组件这里进行判断，可以只定义增加和删除两个事件
    createFood(foodName, foodPrice, imgUrl,id) {
      console.log('监听到子组件事件')
      let foodItem = {
        foodName,
        foodPrice,
        imgUrl,
        id,
        count: 1
      }
      this.order.push(foodItem)
    },
    addFood(foodName) {
      let index = this.order.findIndex(value => value.foodName == foodName)
      this.order[index].count++
    },
    moveFood(foodName) {
      let index = this.order.findIndex(value => value.foodName == foodName)
      this.order.splice(index, 1)
    },
    reduceFood(foodName) {
      let index = this.order.findIndex(value => value.foodName == foodName)
      if (this.order[index].count == 1) this.order.splice(index, 1)
      else this.order[index].count--
    },
    changeFood() {
      // 尽量不要直接操作this.totalPrice
      let totalPrice = 0
      for (let value of this.order) {
        totalPrice += value.foodPrice * value.count
      }
      this.totalPrice = totalPrice
    }
  },
  mounted() {
    // 发起请求
    this.request({
      method: 'GET',
      url: '/main'
    }).then(res => {
      console.log(res)
      let { foodList } = res.data
      // forEach就地改变数组，map返回一个新数组
      let foodType = [...new Set(res.data.foodList.map(value => value.foodType))]
      // 认真品味这个数组处理方法，绝！
      for (let i = 0; i < foodType.length; i++) {
        this.foodList[foodType[i]] = foodList.filter(value => value.foodType == foodType[i])
      }

      // 这里遇到了个很大的问题，v-for监听对象foodList但却没有起作用：
      // 首先，根本原因是这样做虽然更新了this.foodList,但是这个更新在渲染时(v-for启动时)没有被v-for监听到(只有push,shift,splice等方法能监听到，直接赋值不行),
      // 也就是说foodList的更新可能在渲染时或者已经渲染后,而v-for又无法监听正在改变的foodList,所以页面一片空白.那么如果我们在页面渲染之前就已经更新好了foodList呢
      // 接下来我们尝试将mounted改为created，即在页面还没有渲染时就去更新foodList,这样在渲染时就可以监听已经更新的非空的foodList，但最终还是失败了，
      // 原因是因为不管在什么生命周期下，我们都是使用request去发起异步请求啊！异步的方法执行需要很长的时间(在同步事件之后)，就算在created时发起request，也会在mounted后才发起请求更新数据，所以改变声明周期无作用
      // 然而当我们随便插入一个标签后，又可以显示，这是因为插入标签后页面重新渲染，此时v-for获取到了已经更新好的this.foodList
      // 所以我们在每次渲染后强制执行forceUpdate方法就可以了
      this.$forceUpdate()
    })
  }
}
</script>

<style lang="less" scoped>
.main-content {
  width: 375px;
  margin: 20px auto;
  display: flex;
  position: relative;
  .type-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: rgb(241, 241, 241);
    .type-card {
      width: 100%;
      line-height: 60px;
      height: 60px;
      &:hover {
        background-color: #fff;
      }
    }
  }
  .item-list {
    flex: 4;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;
    .food-type {
      width: 100%;
      display: flex;
      flex-direction: column;
      margin-bottom: 30px;
      .type-name {
        text-align: left;
        line-height: 40px;
        height: 40px;
        font-size: 14px;
      }
      .food-card {
        height: 100px;
        display: flex;
        justify-content: flex-start;
        margin-bottom: 20px;
        .img-box {
          border-radius: 5px;
          overflow: hidden;
          margin-right: 10px;
          img {
            height: 100px;
            width: 100px;
          }
        }
        .text-box {
          display: flex;
          flex-direction: column;
          text-align: left;
          .food-name {
            flex: 1;
            font-weight: bold;
          }
          .food-intro {
            flex: 1;
            font-size: 12px;
            color: rgb(255, 153, 0);
          }
          .food-rate {
            flex: 1;
            font-size: 12px;
            color: #666;
          }
          .food-buy {
            flex: 1;
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .price {
              color: orangered;
            }
          }
        }
      }
    }
  }
  .footer {
    position: fixed;
    width: 300px;
    height: 50px;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 25px;
    background-color: black;
    opacity: 0.9;
    color: #fff;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}
</style>
